package io.renren.modules.app.controller;

import com.baidu.aip.ocr.AipOcr;

import io.renren.modules.app.entity.ResidentEntity;
import io.renren.modules.app.entity.Response;
import io.renren.modules.app.entity.UserEntity;

import io.renren.modules.app.service.ResidentService;
import io.renren.modules.app.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;


@RestController
@RequestMapping("/app")
@Slf4j
public class OcrController {

    @Autowired
    private UserService userService;
    @Autowired
    private ResidentService residentService;


    @Autowired
    private ImageUploadController imageUploadController ;

    @PostMapping(value = "/ocrStr")   //司机签名
    public Response ocr1(@RequestParam("userId") int userId, MultipartFile file) throws Exception {
        log.info("进入手写文字识别接口");
        // 通过userId获取用户
        UserEntity user = userService.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        String userName = user.getName();

        AipOcr client = new AipOcr("62808027", "aYnvMrblkDbybEpq5jIyQBp1", "ubaMIJFya0CrssvFrhV8Yml9B8wfOmC2");
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>(4);
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");

        // 参数为二进制数组
        byte[] buf = file.getBytes();
        JSONObject res = client.handwriting(buf, options);

        // 提取并打印出识别的文字
        JSONArray wordsResult = res.getJSONArray("words_result");
        System.out.println(wordsResult);
        String str = "";
        for (int i = 0; i < wordsResult.length(); i++) {
            JSONObject word = wordsResult.getJSONObject(i);
            str = str + word.getString("words");
        }

        // 比对识别结果和用户名
        if (str.equals(userName)) {
            // 上传文件并获取文件URL
            Response uploadResponse = imageUploadController.upload(file);
            Object fileUrl = uploadResponse.getData();
            // 创建一个HashMap来存储str和fileUrl
            HashMap<String, Object> data = new HashMap<>();
            data.put("recognizedText", str);
            data.put("fileUrl", fileUrl);

            return new Response(0, "Success", data);
        } else {
            return new Response(-1, "请重新签名", str);
        }
    }

    @PostMapping(value = "/ocrResidentStr")  //驻厂签名
    public Response ocrResidentStr(@RequestParam("userId") int userId, MultipartFile file) throws Exception {
        log.info("进入驻厂签名识别接口");
        // 通过userId获取用户
        ResidentEntity residentEntity = residentService.getUserById(userId);
        if (residentEntity == null) {
            throw new RuntimeException("用户不存在");
        }
        String userName = residentEntity.getName();

        AipOcr client = new AipOcr("62808027", "aYnvMrblkDbybEpq5jIyQBp1", "ubaMIJFya0CrssvFrhV8Yml9B8wfOmC2");
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>(4);
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");

        // 参数为二进制数组
        byte[] buf = file.getBytes();
        JSONObject res = client.handwriting(buf, options);

        // 提取并打印出识别的文字
        JSONArray wordsResult = res.getJSONArray("words_result");
        String str = "";
        for (int i = 0; i < wordsResult.length(); i++) {
            JSONObject word = wordsResult.getJSONObject(i);
            str = str + word.getString("words");
        }

        // 比对识别结果和用户名
        if (str.equals(userName)) {
            // 上传文件并获取文件URL
            Response uploadResponse = imageUploadController.upload(file);
            Object fileUrl = uploadResponse.getData();

            // 创建一个HashMap来存储str和fileUrl
            HashMap<String, Object> data = new HashMap<>();
            data.put("recognizedText", str);
            data.put("fileUrl", fileUrl);

            return new Response(0, "Success", data);
        } else {
            return new Response(-1, "请重新签名", str);
        }
    }

    @PostMapping(value = "/ocrlicenseStr")   //行驶证识别
    public Response ocrlicenseStr(@RequestParam("userId") int userId, MultipartFile file) throws Exception {
        log.info("进入行驶证识别接口");
        // 通过userId获取用户
        UserEntity user = userService.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        AipOcr client = new AipOcr("62808027", "aYnvMrblkDbybEpq5jIyQBp1", "ubaMIJFya0CrssvFrhV8Yml9B8wfOmC2");
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>(4);
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");

        // 参数为二进制数组
        byte[] buf = file.getBytes();
        JSONObject res = client.vehicleLicense(buf, options);
        try {

            String s = "";
            // 提取并打印出识别的文字

            JSONObject wordsResult = res.getJSONObject("words_result");
            String registrationDate = wordsResult.getJSONObject("注册日期").getString("words");
            String registrationlicense = wordsResult.getJSONObject("车辆识别代号").getString("words");
            String registrationcarnumber = wordsResult.getJSONObject("号牌号码").getString("words");
            if ( registrationDate.compareTo("20160000") <= 0) {
                return new Response(-1, "注册日期为2016年之前", registrationDate);
            }
            // 比对识别结果和用户名
            if (!registrationDate.isEmpty() && !registrationlicense.isEmpty()&&!registrationcarnumber.isEmpty()) {
                // 上传文件并获取文件URL
                Response uploadResponse = imageUploadController.upload(file);
                Object fileUrl = uploadResponse.getData();
                // 创建一个DateTimeFormatter对象
                DateTimeFormatter originalFormat = DateTimeFormatter.ofPattern("yyyyMMdd");
                DateTimeFormatter targetFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                // 使用parse()方法将字符串转换为LocalDate
                LocalDate date = LocalDate.parse(registrationDate, originalFormat);
                // 添加时间部分
                LocalDateTime dateTime = date.atStartOfDay();
                // 使用format()方法将LocalDateTime转换为字符串
                String formattedString = dateTime.format(targetFormat);
                user.setDatetime(formattedString);
                user.setVehiclenumber(registrationlicense);
                userService.updateById(user);
                // 创建一个HashMap来存储str和fileUrl
                HashMap<String, Object> data = new HashMap<>();
                data.put("vehiclenumber",registrationlicense );
                data.put("datetime",formattedString);
                data.put("carnumber",registrationcarnumber);
                data.put("fileUrl", fileUrl);

                return new Response(0, "Success", data);
            } else {
                return new Response(-1, "注册日期为2016年之前", registrationDate);
            }

        } catch (JSONException e) {
            return new Response(1, "证件类型不符或者拍摄不清楚", null);
        }
    }
}



